package com.blue.base.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blue.base.demo.entity.User;
import com.blue.base.demo.mappers.UserMapper;
import com.blue.base.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author liulei
 * @version 2.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    /**
     * 用户类型：微信
     */
    public static final Integer WX_USER_TYPE = 2;

    private final UserMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMobileByWxInfo(String openId, String unionId, String mobilePhone) {
        log.info("wx|auth|user|update|mobile|{}|{}|{}", openId, unionId, mobilePhone);
        User user = new User();
        user.setUserType(WX_USER_TYPE);
        this.mapper.update(user, new LambdaQueryWrapper<User>().eq(User::getOpenid, openId).eq(User::getUnionid, unionId));
    }

    @Override
    public User validateUserExist(String openId, String unionId) {
        log.info("wx|auth|user|validate|by|{}|{}", openId, unionId);
        return mapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenid, openId).eq(User::getUnionid, unionId).eq(User::getUserType, WX_USER_TYPE));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveNewWeChatUser(User user) {
        log.info("wx|auth|user|save|{}", user);
        Date date = new Date();
        user.setCreateTime(date);
        this.mapper.insert(user);
    }
}
